package org.springframework.beans.factory.xml;

import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class BeansDtdResolver implements EntityResolver {

    private static final String DTD_EXTENSION = ".dtd";
    
    private static final String[] DTD_NAMES = new String[]{"spring-beans", "spring-beans-2.0"};
    
    /**
     * @param publicId String 'publicId: -//SPRING//DTD BEAN 2.0//EN'
     * @param systemId String 'http://www.springframework.org/dtd/spring-beans-2.0.dtd'
     */
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
            int lastPathSeperator = systemId.lastIndexOf("/");
            for (String dtdName : DTD_NAMES) {
                int dtdNameStart = systemId.indexOf(dtdName);
                if (dtdNameStart > lastPathSeperator) {
                    String file = systemId.substring(dtdNameStart);
                    Resource resource = new ClassPathResource(file, this.getClass());
                    InputSource inputSource = new InputSource(resource.getInputStream());
                    inputSource.setPublicId(publicId);
                    inputSource.setSystemId(systemId);
                    return inputSource;
                }
            }
        }
        return null;
    }

}
